package algorithm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class T00438 {
    public static void main(String[] args) {
        String s = "cbaebabacd";
        String p = "abc";
        System.out.println(new Solution().findAnagrams(s, p));
    }

    static class Solution {
        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> list = new ArrayList<>();
            Map<Character, Integer> need = new HashMap<>();
            Map<Character, Integer> window = new HashMap<>();
            for (int i = 0; i < p.length(); i ++) {
                char c = p.charAt(i);
                need.put(c, need.getOrDefault(c, 0) + 1);
            }

            int right = 0, start = 0, valid = 0, len = p.length();
            while (right < s.length()) {
                char c = s.charAt(right);
                if (need.containsKey(c)) {
                    window.put(c, window.getOrDefault(c, 0) + 1);
                    if (window.get(c).equals(need.get(c))) {
                        valid ++;
                    }
                }
                right ++;

                if (right <= len) {
                    if (valid == len) {
                        list.add(right - len);
                    }
                    continue;
                }

                char d = s.charAt(right - len - 1);
                if (need.containsKey(d)) {
                    if (window.get(d).equals(need.get(d))) {
                        valid --;
                    }
                    window.put(d, window.get(d) - 1);
                }

                if (valid == len) {
                    list.add(right - len);
                }
            }
            return list;
        }
    }
}
